<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

import {
  Alert as AAlert,
  Form as AForm,
  FormItem as AFormItem,
  InputNumber as AInputNumber,
  Modal as AModal,
  Select as ASelect,
  Spin as ASpin,
  message,
  Modal,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import { saleOrderPickUpReceipt } from '#/api/hm/saleOrderPickUp';
import { ImageUpload } from '#/components/upload';

// TODO: 导入真实的API接口
// import { getOrderRemainingAmount, submitPayment } from '#/api/hm/saleOrder';

// --- 组件通信 (Props & Emits) ---
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  orderId: {
    type: [String, Number],
    required: true,
  },
  // 传入订单数据，以便获取初始的剩余回款额
  orderData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['update:visible', 'success']);

// --- 状态管理 ---
const loading = ref(false);
const formRef = ref(); // 表单引用
const remainingAmount = ref(0); // 剩余回款额

// 表单数据模型
const formState = ref({
  paymentAmount: undefined,
  paymentMethod: undefined,
  attachments: [],
});

// --- 计算属性 ---
// 计算属性，用于动态显示剩余额度提示信息
const remainingAmountText = computed(() => {
  return `当前订单剩余待回款金额为：¥ ${remainingAmount.value.toFixed(2)}`;
});

// --- 表单校验规则 ---
const rules = {
  paymentAmount: [
    {
      required: true,
      validator: async (_rule: any, value: number) => {
        if (value === undefined || value === null) {
          throw '请输入回款金额';
        }
        if (value <= 0) {
          throw '回款金额必须大于0';
        }
        if (value > remainingAmount.value) {
          throw '回款金额不能超过剩余待回款额度';
        }
      },
      trigger: 'change',
    },
  ],
  paymentMethod: [
    { required: true, message: '请选择回款方式', trigger: 'change' },
  ],
};

// --- 核心方法 ---

// 当弹窗显示时，获取最新的剩余回款额
async function fetchRemainingAmount() {
  loading.value = true;
  try {
    // 模拟API返回
    const amount = Number.parseFloat(
      props.orderData?.refundSurplusNum?.replace(/,/g, ''),
    );
    remainingAmount.value = amount;
  } catch (error) {
    console.error('获取剩余回款额失败:', error);
    message.error('获取订单信息失败，无法进行回款操作');
    handleCancel();
  } finally {
    loading.value = false;
  }
}

// 监听弹窗的显示状态
watch(
  () => props.visible,
  (isVisible) => {
    if (isVisible) {
      // 重置表单状态
      formRef.value?.resetFields();
      formState.value.attachments = [];
      // 获取最新数据
      fetchRemainingAmount();
    }
  },
);

// 处理弹窗关闭
function handleCancel() {
  emit('update:visible', false);
}

// 处理表单提交
async function handleSubmit() {
  try {
    // 触发表单校验
    await formRef.value.validate();
    loading.value = true;

    // 构造提交给后端的数据
    const formData = new FormData();
    formData.append('saleOrderId', props.orderId as string);
    formData.append('pickUpNum', formState.value.paymentAmount!);
    formData.append('method', formState.value.paymentMethod!);
    formData.append('pickUpTime', dayjs().format('YYYY-MM-DD HH:mm:ss'));
    formData.append('pickUpType', '0');
    const attachmentUrls = formState.value.attachments.join(',');
    formData.append('file', attachmentUrls);
    Modal.confirm({
      title: '提示',
      okType: 'danger',
      content: `请核对信息是否正确，确定提交吗？`,
      onOk: async () => {
        await saleOrderPickUpReceipt(formData);
        emit('success'); // 通知父组件刷新数据
        handleCancel(); // 关闭弹窗
      },
    });
  } catch (error) {
    console.error('回款提交失败:', error);
    // 如果校验失败，错误信息会自动显示在表单上，无需额外处理
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <AModal
    v-model:visible="props.visible"
    title="发起收款"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirm-loading="loading"
    destroy-on-close
  >
    <ASpin :spinning="loading">
      <AAlert
        :message="remainingAmountText"
        type="info"
        show-icon
        class="mb-4"
      />
      <AForm ref="formRef" :model="formState" :rules="rules" layout="vertical">
        <AFormItem label="回款金额" name="paymentAmount">
          <AInputNumber
            v-model:value="formState.paymentAmount"
            placeholder="请输入本次回款金额"
            :min="0"
            :max="remainingAmount"
            :precision="2"
            style="width: 100%"
            addon-before="¥"
          />
        </AFormItem>
        <AFormItem label="回款方式" name="paymentMethod">
          <ASelect
            v-model:value="formState.paymentMethod"
            placeholder="请选择回款方式"
          >
            <!-- TODO: 此处可以使用字典或从API获取回款方式 -->
            <a-select-option value="alipay">支付宝</a-select-option>
            <a-select-option value="wechatpay">微信支付</a-select-option>
            <a-select-option value="bank_transfer">银行转账</a-select-option>
            <a-select-option value="cash">现金</a-select-option>
            <a-select-option value="pos">POS机刷卡</a-select-option>
          </ASelect>
        </AFormItem>
        <AFormItem label="证明材料" name="attachments">
          <!--使用 ImageUpload 组件 -->
          <ImageUpload
            v-model:value="formState.attachments"
            :max-number="3"
            result-field="url"
            multiple
          />
        </AFormItem>
      </AForm>
    </ASpin>
  </AModal>
</template>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}
</style>
